#!/usr/bin/python
#-*-coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = [u'GuiPart']

u"""
GuiPart desc
"""

from Qt4 import QtGui
from Qt4.QtCore import SIGNAL

from handler import HandlerPart

from pyLot.core import get_data
from pyLot.qtgui import (generate_pyfile_from_uifile, GuiContainerEditor,
                         ToolWidget)

generate_pyfile_from_uifile(__name__, src=get_data(__name__, u'designer.ui'))
from ._designer import Ui_Divider
class GuiPart(Ui_Divider, ToolWidget, QtGui.QWidget):
  """
  A very simple divider GUI
  """
  identifier = 'pyLot.toolwidget.sample'
  main_icon = get_data(__name__, u'icons/compute.png')
  title = u'Toolwidget Example'

  def __init__(self):
    QtGui.QWidget.__init__(self)
    self.setupUi(self) # Designer file initialization
    ToolWidget.__init__(self)

    self._handler = HandlerPart()

    # Widget creation
    self._createPreferences()
    self._createActions()
    self._createConnexions()
    self._createMenu()
    self._createToolBars()

  # ============================================================================
  # Widget Creation
  # ============================================================================

  def _createActions(self):
    u"""
    See 'designer.ui' file (Qt Designer file)
    """
    pass

  def _createConnexions(self):
    # Computing actions
    self.connect(self.action_compute, SIGNAL('triggered()'),
                 self._onActionComputeTriggered)
    self.connect(self.action_expert, SIGNAL('triggered()'),
                 self._onActionComputeTriggered)
    self.connect(self.button_compute, SIGNAL('clicked()'),
                 self.action_compute, SIGNAL('triggered()'))

    # Pref/widget synchronisation
    datum_id = hex(id(self.handler.opt[u'computation']['precision']))
    self.connect(self.pref, SIGNAL('datumWithId%sChanged()' % datum_id),
                 self.action_compute, SIGNAL('triggered()'))

  def _createPreferences(self):
    self._pref = GuiContainerEditor(self.handler.opt[u'computation'])

  def _createMenu(self):
    self.menu_divide = QtGui.QMenu()
    self.menu_divide.setObjectName(u'menu_divide')
    self.addMenu_(self.menu_divide)

  def _createToolBars(self):
    self.tool_bar_divide = QtGui.QToolBar()
    self.tool_bar_divide.setObjectName(u'tool_bar_divide')
    self.addToolBar_(self.tool_bar_divide)

  # ============================================================================
  # Widget dynamic changes
  # ============================================================================

  def _fillMenus(self, level):
    self._fill(self.menu_divide, [
      self.action_compute,
      (self.action_expert, u'expert')
      ])

  def _fillToolBars(self, level):
    self._fill(self.tool_bar_divide, [
      self.action_compute,
      (self.action_expert, u'expert')
      ])

  def _decorate (self):
    self.action_compute.setIcon(self._icon(u'compute.png'))
    self.action_expert.setIcon(self._icon(u'expert.png'))

  def _translate(self):
    self._setTexts([
      (self, self.tr_(u'Sample')),
      (self.menu_divide, self.tr_(u'Divide')),
      (self.tool_bar_divide, self.tr_(u'Divide ToolBar'))
      ])

  # ============================================================================
  # Widget/HandlerPart Connections
  # ============================================================================

  def _onActionComputeTriggered(self):
    try :
      a = int(self.line_a.text())
      b = int(self.line_b.text())
    except ValueError :
      ret = QtGui.QMessageBox.critical(self, self.tr_(u"ValueError"),
       self.tr_(u"Values must be type of int"), QtGui.QMessageBox.Ok)
    else :
      try :
        result = unicode(self.handler.divide(a, b))
      except ValueError :
        ret = QtGui.QMessageBox.critical(self, u"ZeroDivisionError",
         self.tr_(u"You cannot divide by zero, please change second value."),
         QtGui.QMessageBox.Ok)
      else :
        self.line_result.clear()
        self.line_result.insert(result)

  # ============================================================================
  # Widget Public Methods
  # ============================================================================

  def setDivideValueA (self, value):
    u"""
    :param value: the dividend value
    :type value: :obj:`value`
    """
    self.line_a.setValue(unicode(value))

  def setDivideValueB (self, value):
    u"""
    :param value: the divisor value
    :type value: :obj:`value`
    """
    self.line_b.setValue(unicode(value))

if __name__ == u"__main__":
  from Qt4.QtGui import QApplication
  app = QApplication([])
  gui = GuiPart()
  gui.show()
  ret = app.exec_()
